package com.adhere.auth.service.impl;

import com.adhere.auth.pojo.LoginBody;
import com.adhere.auth.pojo.LoginUser;
import com.adhere.auth.pojo.RbacUser;
import com.adhere.auth.remote.RemoteUserService;
import com.adhere.auth.service.LoginService;
import com.adhere.common.pojo.Result;
import com.adhere.common.exception.ServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 *
 * @author WT
 * @date 2022/02/07 14:37:15
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final RemoteUserService remoteUserService;

    public LoginServiceImpl (RemoteUserService remoteUserService) {
        this.remoteUserService = remoteUserService;
    }


    @Override
    public LoginUser login(LoginBody loginBody) {

        // == 校验用户是否合法 ==
        String username = loginBody.getUsername();

        // 查询用户信息
        Result<LoginUser> userResult = remoteUserService.getUserByLoginName(username);

        if (HttpStatus.INTERNAL_SERVER_ERROR.value() == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        if (userResult == null || userResult.getData() == null) {
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        RbacUser user = userResult.getData().getRbacUser();

        if (user.getIsDeleted()) {
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }

        if (user.getIsLocked()) {
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (bCryptPasswordEncoder.matches(loginBody.getPassword(), user.getPassword())) {
            throw new ServiceException("用户/密码错误");
        }

        return userResult.getData();

    }

}
